package org.muninn.niagara.structures;

import javax.baja.sys.BObject;
import javax.baja.sys.Sys;
import javax.baja.sys.Type;

/**
 * 
 * Non-generic implementation of a Stack for use on JACES (which do not support new enough versions of Java to use the standard stack implementation).
 *
 * @author Conor Freeland
 * @creation Jan 2013
 *
 */
public class BStack extends BObject
{
  private String[] contents = new String[8];
  private int ptr = 0;
  
  /**
   * Constructor for the class.
   */
  public BStack() {}
  
  /**
   * Adds new item to the top of the stack.
   * @param string  string to be added to the top of the stack
   */
  public void push(String string)
  {
    if (ptr == contents.length)
      resize();
    
    contents[ptr] = string;
    ptr++;
  }
  
  /**
   * Removes the item on top of the stack, and make the item beneath it visible.
   * @return item formerly on top of the stack
   */
  public String pop()
  {
    if (ptr == 0)
      return null;
    
    else
    {
      ptr--;
      String temp = contents[ptr];
      contents[ptr] = null;
      return temp;
    }
  }
  
  /**
   * Returns the top item of the stack without removing it.
   * @return item on top of the stack
   */
  public String peek() { return contents[ptr - 1]; }
  
  /**
   * Checks if the stack contains any items by looking at the position of the stack pointer.
   * @return true/false for the stack being emtpy/not empty, respectively
   */
  public boolean isEmpty() { return (ptr == 0); }
  
  /**
   * Returns the length of the array on which the stack is based.
   * @return <code>length</code> property of the base array
   */
  public int size() { return contents.length; }
  
  /**
   * Creates new array twice the size of the original, moves all items from the original into the larger array, and renames the larger array to be the base array.
   */
  private void resize()
  {
    String newArray[] = new String[contents.length * 2];
    for (int i = 0; i < contents.length; i ++)
      newArray[i] = contents[i];
    contents = newArray;
  }
  
  public static final Type TYPE = Sys.loadType(BStack.class);
  public Type getType() { return TYPE; }
}
